#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;

class Sock
{
public:
    Sock(string server_ip, int16_t server_port)
    {
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = inet_addr(server_ip.c_str());
        server.sin_port = htons(server_port);

        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            cerr << "创建套接字失败" << endl;
            exit(-1);
        }
        cout << "创建套接字成功" << endl;

        int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
        if (n < 0)
        {
            cerr << "获取连接失败" << endl;
            exit(-1);
        }
        cout << "获取连接成功" << endl;
    }
    void Start()
    {
        while (true)
        {
            string inbuffer;
            cout << "请输入信息:";
            getline(cin, inbuffer);
            int n = write(sockfd, inbuffer.c_str(), sizeof(inbuffer));
            if (n > 0)
            {
                char outbuffer[1024];
                int m = read(sockfd, outbuffer, sizeof(outbuffer));
                if (m > 0)
                {
                    outbuffer[m] = '\0';
                    cout << "来自服务器响应 # " << outbuffer << endl;
                }
                else
                {
                    cerr << "读取失败" << endl;
                    break;
                }
            }
            else
            {
                cerr << "发送失败" << endl;
            }
        }
    }

private:
    int sockfd;
    struct sockaddr_in server;
};

// ./tcp_client ip port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cout << "正确用法:./tcp_client server_ip server_port" << endl;
        exit(-1);
    }
    string server_ip = argv[1];
    int16_t server_port = stoi(argv[2]);
    Sock sock(server_ip, server_port);
    sock.Start();
    return 0;
}